#coding=utf8


import urllib2
import urllib
import re
import os
from xml.dom import minidom
from config import PATH
#import proxy


PAT_SINGER = re.compile(r'function\s+?openhotmb.+?encodeURIComponent\("(.+?)"\)', re.S)
URL_SINGER = 'http://mp3.baidu.com/singerlist/%s.html' 
def get_musician(name):
    url = URL_SINGER % urllib.quote(name)
    try:
        text = urllib2.urlopen( url ).read()
    except Exception, e:
        print 'Error get_musician:', str(e)
        print url
        return None
    res = PAT_SINGER.search( text )
    if res:
        return res.group( 1 )
    return None


PAT_ENCODING = re.compile(r'encoding="(.+?)"', re.I)
URL_SONG_LIST = 'http://box.zhangmen.baidu.com/albumid/%s.html'
def get_songs(musician):
    url = URL_SONG_LIST % musician
    try:
        text = urllib2.urlopen( url ).read()
    except Exception, r:
        print 'Error get_songs:', str(e)
        print url
        return None
    res = PAT_ENCODING.search( text )
    if res:
        encoding = res.group(1)
    else:
        encoding = 'gb2312'
    if 'gb' in encoding:
        text = text.replace(encoding, 'utf-8').decode('gbk').encode('utf8')
    else:
        text = text.replace(encoding, 'utf-8').decode(encoding).encode('utf8')
    doc = minidom.parseString( text )
    names = doc.documentElement.getElementsByTagName('name')
    songs = []
    for n in names:
        songs.append( n.firstChild.nodeValue.encode('gbk') )
    return songs


PAT_MP3 = re.compile(r'<decode><!\[CDATA\[(.+?)\]\]></decode>', re.S)
URL_MP3 = 'http://box.zhangmen.baidu.com/x?op=12&count=1&mtype=1&title=%s'
URL_SONG = 'http://zhangmenshiting.baidu.com/data2/music/%s/%s'
def song_url(song):
    url = URL_MP3 % (song,)
    try:
        text = urllib2.urlopen( url ).read()  ###
    except Exception, e:
        print 'Error song_url:', str(e)
        print url
        return -1
    res = PAT_MP3.search(text)
    if res:
        mp3 = res.group(1)
        sid = mp3.split('.mp3')[0]
        return URL_SONG % (sid, mp3, )
    return 0


PAT_FN = re.compile(r'filename="(.+?)"', re.I)
PAT_ILLEGAL = re.compile(r'[\\/:*?"<>|]', re.S)
def download(path, title, url):
    try:
        r = urllib2.urlopen( url )
    except Exception, e:
        print 'Error download:', str(e)
        print url
        if '401' in str(e):
            return 0
        return -1
    headers = r.headers.headers
    fn = ''
    for h in headers:
        res = PAT_FN.search(h)
        if res:
            fn = path + PAT_ILLEGAL.sub('',res.group(1))
            break
    if not fn:
        fn = path + title + '.mp3'
    print fn
    fw = open(fn, 'wb')
    fw.write( r.read() )
    fw.close()
    return 1


def run(name):
    m = get_musician(name)
    if not m:
        print 'no such singer'
        return None
    songs = get_songs( m )
    print '# of songs:', len(songs)
    
    path = (PATH + name + '/')
    if not os.path.isdir(path):
        os.makedirs( path )
        
    for i in xrange(0, len(songs)):
        s = songs[i]
        title = s.split('$', 1)[0]
        print i, 'downloading... ', title
        url = song_url(s)
        if url == -1:
            break
        elif url == 0:
            print 'no this song'
            continue
        if download( path, title, url ) == -1:
            break
        

if __name__ == '__main__':
    name = raw_input('singer:\n')
    run(name)
